'use client';

// 云存储账号管理页面
// REF: 云存储账号管理-API文档@v1.0.0

import React, { useEffect, useState } from 'react';
import {
  Plus,
  Search,
  Filter,
  MoreHorizontal,
  Edit,
  Trash2,
  Cloud,
  User,
  Database,
  Calendar,
  Key,
  ToggleLeft,
  ToggleRight,
  FolderOpen
} from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { useAuth } from '@/contexts/AuthContext';
import { adminApi } from '@/services/api';
import { cloudAccountApi, CloudStorageAccount, CreateCloudAccountRequest, UpdateCloudAccountRequest } from '@/services/cloudAccountApi';
import { formatBytes, formatDate } from '@/lib/utils';
import { CloudFilesDialog } from '@/components/cloud-files/CloudFilesDialog';

export default function CloudAccountsPage() {
  const { isAdmin } = useAuth();
  const [accounts, setAccounts] = useState<CloudStorageAccount[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedProvider, setSelectedProvider] = useState<string>('all');
  const [selectedStatus, setSelectedStatus] = useState<string>('all');
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [showFilesDialog, setShowFilesDialog] = useState(false);
  const [selectedAccount, setSelectedAccount] = useState<CloudStorageAccount | null>(null);
  const [detailAccount, setDetailAccount] = useState<CloudStorageAccount | null>(null);
  const [filesAccount, setFilesAccount] = useState<CloudStorageAccount | null>(null);
  
  // 创建账号表单数据
  const [createAccountData, setCreateAccountData] = useState<CreateCloudAccountRequest>({
    cloudProvider: 'tianyi',
    cloudAccount: '',
    cloudPassword: '',
    cloudToken: '',
    cloudTokenInfo: {},
    rootDirectoryId: '',
    storageQuota: 10 * 1024 * 1024 * 1024, // 10GB
    isActive: true
  });

  // 编辑账号表单数据
  const [editAccountData, setEditAccountData] = useState<UpdateCloudAccountRequest>({
    cloudProvider: '',
    cloudAccount: '',
    cloudPassword: '',
    cloudToken: '',
    cloudTokenInfo: {},
    rootDirectoryId: '',
    storageQuota: 0,
    isActive: true,
    isOnline: false,
    cloudExpiresAt: ''
  });

  // 加载云存储账号列表
  const loadAccounts = async () => {
    try {
      setLoading(true);
      const response = await cloudAccountApi.getCloudAccounts({
        cloud_provider: selectedProvider === 'all' ? undefined : selectedProvider,
        is_active: selectedStatus === 'all' ? undefined : selectedStatus === 'active',
        search: searchTerm || undefined
      });
      
      if (response.success && response.data && response.data.items) {
        setAccounts(response.data.items);
      }
    } catch (error) {
      console.error('Failed to load cloud accounts:', error);
    } finally {
      setLoading(false);
    }
  };



  // 初始加载
  useEffect(() => {
    if (isAdmin) {
      loadAccounts();
    }
  }, [isAdmin]);

  // 搜索和筛选变化时重新加载
  useEffect(() => {
    if (isAdmin) {
      loadAccounts();
    }
  }, [searchTerm, selectedProvider, selectedStatus, isAdmin]);

  // 创建云存储账号
  const handleCreateAccount = async () => {
    try {
      const response = await cloudAccountApi.createCloudAccount(createAccountData);
      if (response.success) {
        setShowCreateDialog(false);
        loadAccounts();
        // 重置表单
        setCreateAccountData({
          cloudProvider: 'tianyi',
          cloudAccount: '',
          cloudPassword: '',
          cloudToken: '',
          cloudTokenInfo: {},
          rootDirectoryId: '',
          storageQuota: 10 * 1024 * 1024 * 1024,
          isActive: true
        });
      }
    } catch (error) {
      console.error('Failed to create cloud account:', error);
    }
  };

  // 更新云存储账号
  const handleUpdateAccount = async () => {
    if (!selectedAccount) return;
    
    try {
      const response = await cloudAccountApi.updateCloudAccount(selectedAccount.id, editAccountData);
      if (response.success) {
        setShowEditDialog(false);
        loadAccounts();
      }
    } catch (error) {
      console.error('Failed to update cloud account:', error);
    }
  };

  // 删除云存储账号
  const handleDeleteAccount = async () => {
    if (!selectedAccount) return;
    
    try {
      const response = await cloudAccountApi.deleteCloudAccount(selectedAccount.id);
      if (response.success) {
        setShowDeleteDialog(false);
        loadAccounts();
      }
    } catch (error) {
      console.error('Failed to delete cloud account:', error);
    }
  };

  // 打开编辑对话框
  const openEditDialog = (account: CloudStorageAccount) => {
    setSelectedAccount(account);
    setEditAccountData({
      cloudProvider: account.cloudProvider,
      cloudAccount: account.cloudAccount,
      cloudPassword: '',
      cloudToken: '',
      cloudTokenInfo: {},
      rootDirectoryId: account.rootDirectoryId,
      storageQuota: account.storageQuota,
      isActive: account.isActive,
      isOnline: account.isOnline || false,
      cloudExpiresAt: account.cloudExpiresAt
    });
    setShowEditDialog(true);
  };

  // 打开删除对话框
  const openDeleteDialog = (account: CloudStorageAccount) => {
    setSelectedAccount(account);
    setShowDeleteDialog(true);
  };

  // 检测云存储账号
  const handleCheckAccount = async (accountId: number) => {
    try {
      console.log('开始检测云存储账号:', {
        accountId,
        timestamp: new Date().toISOString()
      });
      const response = await cloudAccountApi.checkCloudAccount(accountId);
      console.log('检测云存储账号响应:', {
        accountId,
        success: response.success,
        data: response.data,
        message: response.message,
        timestamp: new Date().toISOString()
      });
      if (response.success) {
        // 重新加载账号列表以获取最新状态
        loadAccounts();
      }
    } catch (error) {
      console.error('Failed to check cloud account:', {
        accountId,
        error: error instanceof Error ? error.message : error,
        stack: error instanceof Error ? error.stack : undefined,
        timestamp: new Date().toISOString()
      });
    }
  };

  // 登录云存储账号
  const handleLoginAccount = async (accountId: number) => {
    try {
      console.log('开始登录云存储账号:', {
        accountId,
        timestamp: new Date().toISOString()
      });
      const response = await cloudAccountApi.loginCloudAccount(accountId);
      console.log('登录云存储账号响应:', {
        accountId,
        success: response.success,
        data: response.data,
        message: response.message,
        timestamp: new Date().toISOString()
      });
      if (response.success) {
        // 重新加载账号列表以获取最新状态
        loadAccounts();
      }
    } catch (error) {
      console.error('Failed to login cloud account:', {
        accountId,
        error: error instanceof Error ? error.message : error,
        stack: error instanceof Error ? error.stack : undefined,
        timestamp: new Date().toISOString()
      });
    }
  };

  // 查看账号详情
  const handleViewDetail = async (account: CloudStorageAccount) => {
    try {
      // 获取包含敏感信息的完整账号详情
      const response = await cloudAccountApi.getCloudAccount(account.id);
      if (response.success && response.data) {
        setDetailAccount(response.data);
        setShowDetailDialog(true);
      }
    } catch (error) {
      console.error('Failed to get cloud account detail:', error);
    }
  };

  // 查看文件管理
  const handleViewFiles = (account: CloudStorageAccount) => {
    setFilesAccount(account);
    setShowFilesDialog(true);
  };

  if (!isAdmin) {
    return (
      <div className="flex items-center justify-center h-full">
        <p>您没有权限访问此页面</p>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-6">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold">云存储账号管理</h1>
        <Button onClick={() => setShowCreateDialog(true)}>
          <Plus className="mr-2 h-4 w-4" /> 添加账号
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>云存储账号列表</CardTitle>
          <CardDescription>管理用户绑定的云存储账号</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center gap-4 mb-4">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  type="search"
                  placeholder="搜索账号..."
                  className="pl-8"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
            </div>
            <Select
              value={selectedProvider}
              onValueChange={setSelectedProvider}
            >
              <SelectTrigger className="w-[180px]">
                <SelectValue placeholder="云存储提供商" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部提供商</SelectItem>
                <SelectItem value="tianyi">天翼云盘</SelectItem>
              </SelectContent>
            </Select>
            <Select
              value={selectedStatus}
              onValueChange={setSelectedStatus}
            >
              <SelectTrigger className="w-[180px]">
                <SelectValue placeholder="账号状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部状态</SelectItem>
                <SelectItem value="active">启用</SelectItem>
                <SelectItem value="inactive">禁用</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>ID</TableHead>
                  <TableHead>用户ID</TableHead>
                  <TableHead>提供商</TableHead>
                  <TableHead>账号</TableHead>
                  <TableHead>存储配额</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>在线状态</TableHead>
                  <TableHead>过期时间</TableHead>
                  <TableHead>创建时间</TableHead>
                  <TableHead>文件</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={11} className="text-center py-4">
                      加载中...
                    </TableCell>
                  </TableRow>
                ) : accounts.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={11} className="text-center py-4">
                      暂无数据
                    </TableCell>
                  </TableRow>
                ) : (
                  accounts.map((account) => (
                    <TableRow key={account.id}>
                      <TableCell>{account.id}</TableCell>
                      <TableCell>{account.userId}</TableCell>
                      <TableCell>
                        {account.cloudProvider === 'tianyi' ? (
                          <Badge variant="outline">天翼云盘</Badge>
                        ) : (
                          account.cloudProvider
                        )}
                      </TableCell>
                      <TableCell>{account.cloudAccount}</TableCell>
                      <TableCell>{formatBytes(account.storageQuota)}</TableCell>
                      <TableCell>
                        {account.isActive ? (
                          <Badge variant="success">启用</Badge>
                        ) : (
                          <Badge variant="destructive">禁用</Badge>
                        )}
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          {account.isOnline ? (
                            <Badge variant="success">在线</Badge>
                          ) : (
                            <Badge variant="secondary">离线</Badge>
                          )}
                        </div>
                      </TableCell>
                      <TableCell>{formatDate(account.cloudExpiresAt)}</TableCell>
                      <TableCell>{formatDate(account.createdAt)}</TableCell>
                      <TableCell>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleViewFiles(account)}
                        >
                          <FolderOpen className="h-4 w-4" />
                        </Button>
                      </TableCell>
                      <TableCell>
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button variant="ghost" size="icon">
                              <MoreHorizontal className="h-4 w-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuLabel>操作</DropdownMenuLabel>
                            <DropdownMenuItem onClick={() => handleViewDetail(account)}>
                              <Database className="mr-2 h-4 w-4" /> 详情
                            </DropdownMenuItem>
                            <DropdownMenuItem onClick={() => handleViewFiles(account)}>
                              <FolderOpen className="mr-2 h-4 w-4" /> 文件
                            </DropdownMenuItem>
                            {!account.isOnline && (
                              <DropdownMenuItem onClick={() => handleLoginAccount(account.id)}>
                                <Key className="mr-2 h-4 w-4" /> 登录
                              </DropdownMenuItem>
                            )}
                            {account.isOnline && (
                              <DropdownMenuItem onClick={() => handleCheckAccount(account.id)}>
                                <Cloud className="mr-2 h-4 w-4" /> 检测
                              </DropdownMenuItem>
                            )}
                            <DropdownMenuItem onClick={() => openEditDialog(account)}>
                              <Edit className="mr-2 h-4 w-4" /> 编辑
                            </DropdownMenuItem>
                            <DropdownMenuSeparator />
                            <DropdownMenuItem
                              className="text-destructive"
                              onClick={() => openDeleteDialog(account)}
                            >
                              <Trash2 className="mr-2 h-4 w-4" /> 删除
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {/* 创建账号对话框 */}
      <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>添加云存储账号</DialogTitle>
            <DialogDescription>
              添加一个新的云存储账号，目前支持天翼云盘。
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="cloudProvider" className="text-right">
                提供商
              </Label>
              <Select
                value={createAccountData.cloudProvider}
                onValueChange={(value) => setCreateAccountData({
                  ...createAccountData,
                  cloudProvider: value
                })}
              >
                <SelectTrigger className="col-span-3">
                  <SelectValue placeholder="选择提供商" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="tianyi">天翼云盘</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="cloudAccount" className="text-right">
                账号
              </Label>
              <Input
                id="cloudAccount"
                className="col-span-3"
                value={createAccountData.cloudAccount}
                onChange={(e) => setCreateAccountData({
                  ...createAccountData,
                  cloudAccount: e.target.value
                })}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="cloudPassword" className="text-right">
                密码
              </Label>
              <Input
                id="cloudPassword"
                type="password"
                className="col-span-3"
                value={createAccountData.cloudPassword}
                onChange={(e) => setCreateAccountData({
                  ...createAccountData,
                  cloudPassword: e.target.value
                })}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="cloudToken" className="text-right">
                Token
              </Label>
              <Input
                id="cloudToken"
                className="col-span-3"
                value={createAccountData.cloudToken}
                onChange={(e) => setCreateAccountData({
                  ...createAccountData,
                  cloudToken: e.target.value
                })}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="rootDirectoryId" className="text-right">
                根目录ID
              </Label>
              <Input
                id="rootDirectoryId"
                className="col-span-3"
                value={createAccountData.rootDirectoryId}
                onChange={(e) => setCreateAccountData({
                  ...createAccountData,
                  rootDirectoryId: e.target.value
                })}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="storageQuota" className="text-right">
                存储配额(GB)
              </Label>
              <Input
                id="storageQuota"
                type="number"
                className="col-span-3"
                value={createAccountData.storageQuota / (1024 * 1024 * 1024)}
                onChange={(e) => setCreateAccountData({
                  ...createAccountData,
                  storageQuota: parseInt(e.target.value) * 1024 * 1024 * 1024
                })}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="isActive" className="text-right">
                状态
              </Label>
              <div className="flex items-center space-x-2 col-span-3">
                <Switch
                  id="isActive"
                  checked={createAccountData.isActive}
                  onCheckedChange={(checked) => setCreateAccountData({
                    ...createAccountData,
                    isActive: checked
                  })}
                />
                <Label htmlFor="isActive">
                  {createAccountData.isActive ? '启用' : '禁用'}
                </Label>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowCreateDialog(false)}>
              取消
            </Button>
            <Button onClick={handleCreateAccount}>创建</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 编辑账号对话框 */}
      <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>编辑云存储账号</DialogTitle>
            <DialogDescription>
              修改云存储账号信息，留空的字段将保持不变。
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-cloudProvider" className="text-right">
                提供商
              </Label>
              <Select
                value={editAccountData.cloudProvider}
                onValueChange={(value) => setEditAccountData({
                  ...editAccountData,
                  cloudProvider: value
                })}
              >
                <SelectTrigger className="col-span-3">
                  <SelectValue placeholder="选择提供商" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="tianyi">天翼云盘</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-cloudAccount" className="text-right">
                账号
              </Label>
              <Input
                id="edit-cloudAccount"
                className="col-span-3"
                value={editAccountData.cloudAccount || ''}
                onChange={(e) => setEditAccountData({
                  ...editAccountData,
                  cloudAccount: e.target.value
                })}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-cloudPassword" className="text-right">
                密码
              </Label>
              <Input
                id="edit-cloudPassword"
                type="password"
                className="col-span-3"
                placeholder="留空则不修改"
                value={editAccountData.cloudPassword || ''}
                onChange={(e) => setEditAccountData({
                  ...editAccountData,
                  cloudPassword: e.target.value
                })}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-cloudToken" className="text-right">
                Token
              </Label>
              <Input
                id="edit-cloudToken"
                className="col-span-3"
                placeholder="留空则不修改"
                value={editAccountData.cloudToken || ''}
                onChange={(e) => setEditAccountData({
                  ...editAccountData,
                  cloudToken: e.target.value
                })}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-rootDirectoryId" className="text-right">
                根目录ID
              </Label>
              <Input
                id="edit-rootDirectoryId"
                className="col-span-3"
                value={editAccountData.rootDirectoryId || ''}
                onChange={(e) => setEditAccountData({
                  ...editAccountData,
                  rootDirectoryId: e.target.value
                })}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-storageQuota" className="text-right">
                存储配额(GB)
              </Label>
              <Input
                id="edit-storageQuota"
                type="number"
                className="col-span-3"
                value={editAccountData.storageQuota ? editAccountData.storageQuota / (1024 * 1024 * 1024) : ''}
                onChange={(e) => setEditAccountData({
                  ...editAccountData,
                  storageQuota: parseInt(e.target.value) * 1024 * 1024 * 1024
                })}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-isActive" className="text-right">
                状态
              </Label>
              <div className="flex items-center space-x-2 col-span-3">
                <Switch
                  id="edit-isActive"
                  checked={editAccountData.isActive}
                  onCheckedChange={(checked) => setEditAccountData({
                    ...editAccountData,
                    isActive: checked
                  })}
                />
                <Label htmlFor="edit-isActive">
                  {editAccountData.isActive ? '启用' : '禁用'}
                </Label>
              </div>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-isOnline" className="text-right">
                在线状态
              </Label>
              <div className="flex items-center space-x-2 col-span-3">
                <Switch
                  id="edit-isOnline"
                  checked={editAccountData.isOnline || false}
                  onCheckedChange={(checked) => setEditAccountData({
                    ...editAccountData,
                    isOnline: checked
                  })}
                />
                <Label htmlFor="edit-isOnline">
                  {editAccountData.isOnline ? '在线' : '离线'}
                </Label>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowEditDialog(false)}>
              取消
            </Button>
            <Button onClick={handleUpdateAccount}>保存</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除账号确认对话框 */}
      <Dialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>删除云存储账号</DialogTitle>
            <DialogDescription>
              确定要删除此云存储账号吗？此操作不可撤销。
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
            {selectedAccount && (
              <p>
                即将删除账号：<strong>{selectedAccount.cloudAccount}</strong> (ID: {selectedAccount.id})
              </p>
            )}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDeleteDialog(false)}>
              取消
            </Button>
            <Button variant="destructive" onClick={handleDeleteAccount}>
              删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 账号详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="sm:max-w-[600px] max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>云存储账号详情</DialogTitle>
            <DialogDescription>
              查看云存储账号的完整信息，包括登录缓存token信息。
            </DialogDescription>
          </DialogHeader>
          {detailAccount && (
            <div className="space-y-4">
              {/* 基本信息 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-sm font-medium text-gray-500">账号ID</Label>
                  <p className="text-sm">{detailAccount.id}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">用户ID</Label>
                  <p className="text-sm">{detailAccount.userId}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">云服务商</Label>
                  <p className="text-sm">
                    {detailAccount.cloudProvider === 'tianyi' ? (
                      <Badge variant="outline">天翼云盘</Badge>
                    ) : (
                      detailAccount.cloudProvider
                    )}
                  </p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">云盘账号</Label>
                  <p className="text-sm">{detailAccount.cloudAccount}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">存储配额</Label>
                  <p className="text-sm">{formatBytes(detailAccount.storageQuota)}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">根目录ID</Label>
                  <p className="text-sm">{detailAccount.rootDirectoryId || '未设置'}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">账号状态</Label>
                  <p className="text-sm">
                    {detailAccount.isActive ? (
                      <Badge variant="success">启用</Badge>
                    ) : (
                      <Badge variant="destructive">禁用</Badge>
                    )}
                  </p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">在线状态</Label>
                  <p className="text-sm">
                    {detailAccount.isOnline ? (
                      <Badge variant="success">在线</Badge>
                    ) : (
                      <Badge variant="secondary">离线</Badge>
                    )}
                  </p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">过期时间</Label>
                  <p className="text-sm">{formatDate(detailAccount.cloudExpiresAt)}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">最后检测时间</Label>
                  <p className="text-sm">{formatDate(detailAccount.lastCheckAt)}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">创建时间</Label>
                  <p className="text-sm">{formatDate(detailAccount.createdAt)}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">更新时间</Label>
                  <p className="text-sm">{formatDate(detailAccount.updatedAt)}</p>
                </div>
              </div>

              {/* 敏感信息 */}
              <div className="border-t pt-4">
                <h4 className="text-sm font-medium mb-3 text-orange-600">敏感信息</h4>
                <div className="space-y-3">
                  <div>
                    <Label className="text-sm font-medium text-gray-500">云盘密码</Label>
                    <p className="text-sm font-mono bg-gray-100 p-2 rounded break-all">
                      {detailAccount.cloudPassword || '未设置'}
                    </p>
                  </div>
                  <div>
                    <Label className="text-sm font-medium text-gray-500">登录Token</Label>
                    <p className="text-sm font-mono bg-gray-100 p-2 rounded break-all">
                      {detailAccount.cloudToken || '未设置'}
                    </p>
                  </div>
                  <div>
                    <Label className="text-sm font-medium text-gray-500">Token信息</Label>
                    <pre className="text-xs font-mono bg-gray-100 p-2 rounded overflow-x-auto whitespace-pre-wrap">
                      {detailAccount.cloudTokenInfo ? JSON.stringify(JSON.parse(detailAccount.cloudTokenInfo), null, 2) : '未设置'}
                    </pre>
                  </div>
                </div>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDetailDialog(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 文件管理对话框 */}
      {filesAccount && (
        <CloudFilesDialog
          account={filesAccount}
          open={showFilesDialog}
          onOpenChange={setShowFilesDialog}
        />
      )}
    </div>
  );
}